﻿using System.Linq;
using Microsoft.AspNet.SignalR;
using System.Threading.Tasks;

namespace GuideAPI.BasicChat
{
    [Authorize]
    public class ChatHub : Hub
    {
        readonly static ConnectionMapping<string> _connections=new ConnectionMapping<string>();

        public void SendChatMessage(string who, string message)
        {
            string name = Context.User.Identity.Name;

            foreach (string connectionId in _connections.GetConnections(name))
            {
                Clients.Client(connectionId).addChatMessage($"{name}: {message}");
            }

            //single-user groups
            Clients.Group(who).addChatMessage($"{name}: {message}");
        }

        public override Task OnConnected()
        {
            string name = Context.User.Identity.Name;

            _connections.Add(name,Context.ConnectionId);

            //single-user groups
            Groups.Add(Context.ConnectionId, name);

            return base.OnConnected();
        }

        public override Task OnDisconnected(bool stopCalled)
        {
            string name = Context.User.Identity.Name;

            _connections.Remove(name,Context.ConnectionId);

            return base.OnDisconnected(stopCalled);
        }

        public override Task OnReconnected()
        {
            string name = Context.User.Identity.Name;

            if (!_connections.GetConnections(name).Contains(Context.ConnectionId))
            {
                _connections.Add(name,Context.ConnectionId);
            }

            return base.OnReconnected();
        }
    }
}